﻿using CYZH.CommandAssembly.JsonObject;
using CYZH.Common;
using CYZH.Service.Drought;
using SuperWebSocket;
using SuperWebSocket.SubProtocol;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CYZH.CommandAssembly.Command
{
    public class AI : JsonSubCommand<MODISParam>
    {
        protected override void ExecuteJsonCommand(WebSocketSession session, MODISParam commandInfo)
        {
            double[] ext = { 0, 0, 0, 0 };
            OutRasterConfigElement rce = Common.ConfigHelper.GetConfigParamByXzqhCode(commandInfo.XzqhCode);

            string strminx = rce.Extents;
            string[] strext = strminx.Split(',');

            double MinX = Convert.ToDouble(strext[0]);
            double MinY = Convert.ToDouble(strext[1]);
            double MaxX = Convert.ToDouble(strext[2]);
            double MaxY = Convert.ToDouble(strext[3]);
            ext[0] = MinX;// { MinX, MinY, MaxX, MaxY };
            ext[1] = MinY;
            ext[2] = MaxX;
            ext[3] = MaxY;

            string aoifile = rce.ShpFile;
            string cldaoiFile = rce.ChildShpFile;
            string layername = commandInfo.XzqhCode + "_" + commandInfo.FileTime + "_ai";
            string strextents = ext[0] + ", " + ext[1] + ", " + ext[2] + ", " + ext[3];
            //查询数据是否已经做过
            List<ModisResultBean> res = CommonService.queryRasterResult(commandInfo.XzqhCode, commandInfo.FileTime, "AI", "year", null);
            if (res.Count != 0)
            {
                //string filename = res[0].FileName;
                //string filepath= FileOper.GetExitsModisFilePath("MOD09Q1", filename,"NDVI","map")  ;
                //string unixfile1 = filepath.Replace('\\', '/');
                MapFileResult resultstate3 = new MapFileResult();
                resultstate3.process = "100";
                resultstate3.state = "0";
                resultstate3.value = "success";
                resultstate3.LayerName = res[0].LayerName;
                resultstate3.Extents = strextents;
                //resultstate3.MapFile = unixfile1;
                SendJsonMessage(session, resultstate3);
                Logger.Singleton.Debug(String.Format("AI结果已经存在."));
                return;
            }

            List<string> files = new List<string>();
            foreach (string filename in commandInfo.MODISFileList)
            {

                string filepath = FileOper.GetExitsModisFilePath(filename, "GRASS");
                if (!File.Exists(filepath))
                {
                    continue;
                }
                files.Add(filepath);
            }
            if (files.Count == 0)
            {
                Logger.Singleton.Debug("输入文件不存在...");
                ResultState errstate = new ResultState();
                errstate.process = "100";
                errstate.state = "-1";
                errstate.value = "输入文件不存在...";
                SendJsonMessage(session, errstate);
                return;
            }
            string avgfile = FileOper.GenPreGrass(commandInfo.XzqhCode, commandInfo.AvgFile);
            if (!File.Exists(avgfile))
            {
                Logger.Singleton.Debug("文件不存在...");
                ResultState errstate = new ResultState();
                errstate.process = "100";
                errstate.state = "-1";
                errstate.value = avgfile + "文件不存在...";
                SendJsonMessage(session, errstate);
                return;
            }
            string aoiShpFile = FileOper.GenAOIFilePath(aoifile);
            string cldaoiShpFile = FileOper.GenAOIFilePath(cldaoiFile);
            string sfilename = FileOper.GenModisFilePath(layername, "AI");

            AIService aiservice = new AIService();
            int aireater = aiservice.CalculateAI(files[0], avgfile, aoiShpFile, sfilename);
            if (aireater != 0)
            {
                ResultState errstate = new ResultState();
                errstate.process = "100";
                errstate.state = "-1";
                errstate.value = "计算AI出错!";
                SendJsonMessage(session, errstate);
                return;
            }
            //生成统计信息，按当前行政区划的下一级统计
            string  aijson = aiservice.AIStatistics(sfilename, cldaoiShpFile);

            //保存到数据库
            CommonService.saveRasterResult(sfilename, commandInfo.FileTime, commandInfo.XzqhCode, layername, "AI", "", "", "", "year", aijson, null);

            //string unixfile = mapfile.Replace('\\', '/');
            MapFileResult resultstate1 = new MapFileResult();
            resultstate1.process = "100";
            resultstate1.state = "0";
            resultstate1.value = "success";
            resultstate1.LayerName = layername;
            resultstate1.Extents = strextents;
            //resultstate1.MapFile = unixfile;
            SendJsonMessage(session, resultstate1);
            Logger.Singleton.Debug(String.Format("ai结果已经存在，ai文件路径：{0}.", sfilename));

        }
    }
}
